import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
Why SIMPLEGUI?
EVENT DRIVEN PROGRAMMING
It is the programming paradigm where the flow of the program is primarily determined by user actions or events. In this paradigm, the program waits for specific events to occur and then responds accordingly.
EVENT
PROGRAM STRUCTURE
FRAME
A frame is a window, which is a container for the controls, status information, and canvas. A program can create only one frame.
CREATE FRAME
START FRAME
EXAMPLE
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui #frame = simplegui.create_frame(window_name, canvas_width, canvas_height)frame = simplegui.create_frame("New Frame", 200, 300)# Here are the parts of the frame:# window_name = "New Frame"# canvas_width = 200# canvas_height = 300frame.start()
Control objects are placed in the control panel, which is the left-hand part of the frame. They are placed top-down in the order of creation. Status information is at the bottom of the control panel.
OPERATIONS
ADD LABEL TO FRAME CONTROL PANEL
ADD BUTTON TO FRAME CONTROL PANEL
A sample program that allows the user to change the color of the canvas using buttons.
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui# Global variablescanvas_color ="White"# Event handlersdef button_handler_red():global canvas_color canvas_color ="Red"def button_handler_green():global canvas_color canvas_color ="Green"def button_handler_blue():global canvas_color canvas_color ="Blue"def draw(canvas): canvas.draw_polygon([(0, 0), (200, 0), (200, 200), (0, 200)], 0, canvas_color, canvas_color)# Create a frameframe = simplegui.create_frame("Change Canvas Color", 200, 200)# Create buttonsbutton_red = frame.add_button("Red", button_handler_red)button_green = frame.add_button("Green", button_handler_green)button_blue = frame.add_button("Blue", button_handler_blue)# Set the draw handlerframe.set_draw_handler(draw)# Start the frameframe.start()
TRUE FALSE QUIZ
# Buttons# True / False Quiz# This is a sample program that creates a simple 5 question# True / False quiz. You can change the number and type# of questions to create your own!# Note: This is not the most efficient way to design this# program. A better implementation uses lists, but we # haven't learned about those yet. Watch for an improved# version of this program in week 4!import SimpleGUICS2Pygame.simpleguics2pygame as simplegui # Global Variablescanvas_color ="Black"canvas_width =300canvas_height =300question_number =1cur_question =""# Keeps track of the current questioncur_answer =True# Keeps track of the answer to the current questionplayer_answer =Falsepoints =0question_1 ="'R' comes before 'Q' in the alphabet."answer_1 =Falsequestion_2 ="Africa is a continent."answer_2 =Truequestion_3 ="Indentation is not important in CodeSkulptor."answer_3 =Falsequestion_4 ="5 + 2 * 3 = 21"answer_4 =Falsequestion_5 ="Computer Science is AWESOME!!!"answer_5 =True# Alternate set of "questions" - impossible quiz style# Uncomment to use#question_1 = "Zebra."#answer_1 = False#question_2 = "Apple Juice."#answer_2 = True#question_3 = "Happy."#answer_3 = True#question_4 = "Exponent."#answer_4 = False#question_5 = "Potato."#answer_5 = True# Helper Functionsdef print_question():print"Question", question_numberprint cur_questiondef check_answer():global points, cur_question, question_number, cur_answerif player_answer == cur_answer:print"Correct! Good job!" points +=1 next_question()else:print"Incorrect" next_question()def next_question():global cur_question, cur_answer, question_numberif cur_question == question_1: cur_question = question_2 cur_answer = answer_2 question_number +=1 print_question()elif cur_question == question_2: cur_question = question_3 cur_answer = answer_3 question_number +=1 print_question()elif cur_question == question_3: cur_question = question_4 cur_answer = answer_4 question_number +=1 print_question()elif cur_question == question_4: cur_question = question_5 cur_answer = answer_5 question_number +=1 print_question()else:print"End of questions!"print"You scored:", points, "out of", question_number new_game()# Event Handlersdef true_button():global player_answer player_answer =True check_answer()def false_button():global player_answer player_answer =False check_answer()def new_game():global cur_question, points, question_number, cur_answer cur_question = question_1 cur_answer = answer_1 points =0 question_number =1printprint"New Game! Good luck!" print_question()# Frameframe = simplegui.create_frame("Quiz", canvas_width, canvas_height) # Register Event Handlersframe.add_button("True", true_button, 60)frame.add_button("False", false_button, 60)frame.add_button("Restart", new_game, 60)# Start Frame and Gamenew_game()frame.start()
ADD TEXT INPUT BOX TO FRAME CONTROL PANEL
EXAMPLE
"""Input field examples"""# Input fields can be used to call functions multiple times# while the program is running. Here are functions from# week one that can now be called using input fields.# There is a difference: input fields always return strings,# but the methods require numbers. This is solved using the# int() and float() methods.# Remember to hit 'enter' after typing data into the input# fields to give it to the computor. Be careful! If you# enter the wrong type of data, an error can occur.import SimpleGUICS2Pygame.simpleguics2pygame as simplegui # ConstatnsCANVAS_WIDTH =300CANVAS_HEIGHT =300# Input handlersdef num_diagonals(num_sides):""" Given integer num_sides, print number of diagonal for convex polygon with that number of sides """ num_sides =int(num_sides) ans = num_sides * (num_sides -3) //2print("Number of Diagonals:")print(ans)print()def print_triangle_type(degrees):""" Given its largest angle in degrees, prints the type of triangle """ degrees =float(degrees)print("Triangle Type:")if degrees >90and degrees <180:print("Triangle is obtuse!")elif degrees ==90:print("Triangle is right!")elif degrees <90and degrees >0:print("Triangle is acute!")else:print("Triangle does not exist!")print()# Create frameframe = simplegui.create_frame("Functions", CANVAS_WIDTH, CANVAS_HEIGHT, 150) # Register input handlersframe.add_input("Number of sides:", num_diagonals, 100)frame.add_input("Angle measure: (degrees)", print_triangle_type, 100)# Start frameframe.start()
"""Demo of mouse click handler"""import SimpleGUICS2Pygame.simpleguics2pygame as simplegui import math# intialize globalsWIDTH =450HEIGHT =300ball_pos = [WIDTH /2, HEIGHT /2]BALL_RADIUS =15ball_color ="Red"# helper functiondef distance(pt1, pt2):""" Take points pt1 and pt2 (as tuples) Return Euclidean distance between points """return math.sqrt( (pt1[0] - pt2[0]) **2+ (pt1[1] - pt2[1]) **2)# define event handler for mouse click, drawdef click(pos):""" Mouse click handler Updates ball color to green if click is inside ball, Otherwise moves ball to clicked position """global ball_pos, ball_colorif distance(pos, ball_pos) < BALL_RADIUS: ball_color ="Green"else: ball_pos =list(pos) ball_color ="Red"def draw(canvas):""" Draw handler, with canvas as input """ canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Black", ball_color)# create frameframe = simplegui.create_frame("Mouse selection", WIDTH, HEIGHT)frame.set_canvas_background("White")# register event handlerframe.set_mouseclick_handler(click)frame.set_draw_handler(draw)# start frameframe.start()
MOUSE DRAG EXAMPLE
"""Demo of mouse drag handler"""# This program allows the user to move a circle around the # canvas using the mouse.import SimpleGUICS2Pygame.simpleguics2pygame as simplegui # Global VariablesCANVAS_WIDTH =300CANVAS_HEIGHT =300point = [CANVAS_WIDTH /2, CANVAS_HEIGHT /2]# Event Handlersdef draw(canvas):""" Draw handler, takes canvas as input """ canvas.draw_circle(point, 20, 5, "White", "Red")# This is the handler for mouse drag events. Note that it# must take one parameter, a tuple of the position of the# mouse click.def drag(pos):""" Mouse drag handler, updates global variable point """global point point = pos# Frameframe = simplegui.create_frame("Ball Drag", CANVAS_WIDTH, CANVAS_HEIGHT) # Register Event Handlersframe.set_draw_handler(draw)# This is necessary to tell the program what to do with# mouse drag eventsframe.set_mousedrag_handler(drag)# Startframe.start()